﻿using Microsoft.AspNetCore.Mvc;
using OrderStateMachineWebApi_V2.Models;
using OrderStateMachineWebApi_V2.Services;

namespace OrderStateMachineWebApi_V2.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class OrdersController : ControllerBase
    {
        private readonly IOrderService _orderService;

        public OrdersController(IOrderService orderService)
        {
            _orderService = orderService;
        }

        [HttpPost]
        public IActionResult CreateOrder()
        {
            var order = _orderService.CreateOrder();
            return Ok(new
            {
                OrderId = order.Id,
                Status = order.State.StateName
            });
        }

        [HttpGet("{orderId}")]
        public IActionResult GetOrder(string orderId)
        {
            var order = _orderService.GetOrder(orderId);
            if (order == null) return NotFound();

            return Ok(new
            {
                order.Id,
                Status = order.State.StateName,
                order.CreatedAt,
                order.LastUpdated,
                History = order.History
            });
        }

        [HttpGet]
        public IActionResult GetAllOrders()
        {
            var orders = _orderService.GetAllOrders();
            return Ok(orders.Select(o => new
            {
                o.Id,
                Status = o.State.StateName,
                o.CreatedAt,
                o.LastUpdated
            }));
        }

        [HttpPost("{orderId}/process")]
        public IActionResult ProcessOrder(string orderId, [FromBody] OrderActionRequest request)
        {
            var success = _orderService.ProcessOrder(orderId, request.Action);
            if (!success) return BadRequest("Invalid action for current state");

            var order = _orderService.GetOrder(orderId);
            return Ok(new
            {
                Status = order!.State.StateName,
                LastUpdated = order.LastUpdated
            });
        }
    }

    public record OrderActionRequest(OrderAction Action);
}